<template>
  <div :id="mapId" class="amap-container"></div>
</template>

<script>
export default {
  name: 'AMapComponent',
  props: {
    mapId: {
      type: String,
      default: 'aMap'
    },
    startPoint: {
      type: Object,
      default: () => ({ lat: 39.915, lng: 116.404 })
    },
    rescuePoint: {
      type: Object,
      default: () => null
    },
    endPoint: {
      type: Object,
      default: () => null
    },
    zoom: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      map: null,
      AMap: null,
      isMapLoaded: false,
      startMarker: null,
      rescueMarker: null,
      endMarker: null,
      startToRescueLine: null,
      rescueToEndLine: null,
      driving: null,
      retryCount: 0,
      maxRetries: 3
    };
  },
  mounted() {
    // 为了确保DOM已经渲染，使用nextTick
    this.$nextTick(() => {
      this.initMapWithRetry();
    });
  },
  methods: {
    initMapWithRetry() {
      console.log(`尝试初始化地图 (尝试 ${this.retryCount + 1}/${this.maxRetries + 1})`);
      
      // 添加随机延迟，避免多个实例同时初始化
      const delay = Math.floor(Math.random() * 500) + 500;
      
      setTimeout(() => {
        this.initAMap().catch(error => {
          console.error('地图初始化失败:', error);
          
          if (this.retryCount < this.maxRetries) {
            this.retryCount++;
            console.log(`将在2秒后重试初始化地图 (${this.retryCount}/${this.maxRetries})`);
            setTimeout(() => this.initMapWithRetry(), 2000);
          } else {
            this.$emit('map-error', '多次尝试后地图仍无法加载，请刷新页面或检查网络连接');
          }
        });
      }, delay);
    },
    
    async initAMap() {
      console.log('开始初始化高德地图');
      
      // 检查AMap是否存在
      if (!window.AMap) {
        throw new Error('高德地图API未加载，请检查网络连接或刷新页面');
      }
      
      console.log('AMap全局对象已存在');
      this.AMap = window.AMap;
      
      // 初始化地图实例
      await this.initMap();
      
      // 设置标记点和路线
      this.setMapPoints();
      
      // 通知父组件地图已加载
      this.$emit('map-loaded', this.map);
    },
    
    initMap() {
      return new Promise((resolve, reject) => {
        try {
          console.log('初始化地图实例');
          
          const mapContainer = document.getElementById(this.mapId);
          
          if (!mapContainer) {
            throw new Error(`地图容器 ${this.mapId} 不存在`);
          }
          
          // 确保容器有尺寸
          if (mapContainer.clientWidth === 0 || mapContainer.clientHeight === 0) {
            console.warn('地图容器尺寸为0，设置默认尺寸');
            mapContainer.style.width = '100%';
            mapContainer.style.height = '400px';
          }
          
          console.log('创建地图对象');
          this.map = new this.AMap.Map(this.mapId, {
            center: [this.startPoint.lng, this.startPoint.lat],
            zoom: this.zoom,
            resizeEnable: true,
            viewMode: '2D',
            jogEnable: true,
            pitchEnable: false,
            features: ['bg', 'road', 'building', 'point'],
            mapStyle: 'normal'
          });
          
          // 隐藏地图Logo和版权信息
          const logoEls = document.getElementsByClassName('amap-logo');
          const copyrightEls = document.getElementsByClassName('amap-copyright');
          
          if (logoEls && logoEls.length > 0) {
            for (let i = 0; i < logoEls.length; i++) {
              logoEls[i].style.display = 'none';
            }
          }
          
          if (copyrightEls && copyrightEls.length > 0) {
            for (let i = 0; i < copyrightEls.length; i++) {
              copyrightEls[i].style.display = 'none';
            }
          }
          
          // 确保地图已加载完成
          this.map.on('complete', () => {
            console.log('地图加载完成事件触发');
            this.isMapLoaded = true;
            resolve();
          });
          
          // 添加错误处理
          this.map.on('error', (e) => {
            console.error('地图加载出错:', e);
            reject(e);
          });
          
          // 添加超时处理
          setTimeout(() => {
            if (!this.isMapLoaded) {
              reject(new Error('地图加载超时'));
            }
          }, 10000); // 10秒超时
          
        } catch (error) {
          console.error('初始化地图出错:', error);
          reject(error);
        }
      });
    },
    
    setMapPoints() {
      if (!this.isMapLoaded) {
        console.warn('地图尚未加载完成，无法设置点位');
        return;
      }
      
      console.log('设置地图点位和路线');
      
      // 清除之前的标记和路线
      this.clearMapOverlays();
      
      // 添加起点标记
      if (this.startPoint && this.startPoint.lat && this.startPoint.lng) {
        const startPosition = [this.startPoint.lng, this.startPoint.lat];
        this.startMarker = new this.AMap.Marker({
          position: startPosition,
          map: this.map,
          icon: new this.AMap.Icon({
            size: new this.AMap.Size(25, 34),
            image: '//webapi.amap.com/theme/v1.3/markers/n/start.png',
            imageSize: new this.AMap.Size(25, 34)
          }),
          label: {
            content: '司机出发点',
            direction: 'right',
            offset: [10, 0]
          }
        });
        
        // 如果有救援点，规划从起点到救援点的路线
        if (this.rescuePoint && this.rescuePoint.lat && this.rescuePoint.lng) {
          const rescuePosition = [this.rescuePoint.lng, this.rescuePoint.lat];
          this.rescueMarker = new this.AMap.Marker({
            position: rescuePosition,
            map: this.map,
            icon: new this.AMap.Icon({
              size: new this.AMap.Size(25, 34),
              image: '//webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
              imageSize: new this.AMap.Size(25, 34)
            }),
            label: {
              content: '救援地点',
              direction: 'right',
              offset: [10, 0]
            }
          });
          
          // 规划从起点到救援点的路线（蓝色）
          this.planRoute(startPosition, rescuePosition, '#1890ff', line => {
            this.startToRescueLine = line;
          }, 'startToRescue');
        }
      }
      
      // 如果有终点，添加终点标记
      if (this.endPoint && this.endPoint.lat && this.endPoint.lng) {
        const endPosition = [this.endPoint.lng, this.endPoint.lat];
        this.endMarker = new this.AMap.Marker({
          position: endPosition,
          map: this.map,
          icon: new this.AMap.Icon({
            size: new this.AMap.Size(25, 34),
            image: '//webapi.amap.com/theme/v1.3/markers/n/end.png',
            imageSize: new this.AMap.Size(25, 34)
          }),
          label: {
            content: '目的地',
            direction: 'right',
            offset: [10, 0]
          }
        });
        
        // 如果有救援点，规划从救援点到终点的路线
        if (this.rescuePoint && this.rescuePoint.lat && this.rescuePoint.lng) {
          const rescuePosition = [this.rescuePoint.lng, this.rescuePoint.lat];
          
          // 规划从救援点到终点的路线（绿色）
          this.planRoute(rescuePosition, endPosition, '#67c23a', line => {
            this.rescueToEndLine = line;
          }, 'rescueToEnd');
        } else if (this.startPoint && this.startPoint.lat && this.startPoint.lng) {
          // 如果没有救援点但有起点，直接规划从起点到终点的路线
          const startPosition = [this.startPoint.lng, this.startPoint.lat];
          this.planRoute(startPosition, endPosition, '#67c23a', line => {
            this.rescueToEndLine = line;
          }, 'startToEnd');
        }
      }
      
      // 调整地图视野，确保所有点都在视野内
      this.adjustMapView();
    },
    
    planRoute(start, end, strokeColor, callback, routeType) {
      if (!this.isMapLoaded) {
        console.warn('地图尚未加载完成，无法规划路线');
        return;
      }
      
      console.log(`规划路线 ${start} -> ${end}`);
      
      try {
        // 使用AMap.plugin加载驾车路线规划插件
        this.AMap.plugin(['AMap.Driving'], () => {
          // 创建驾车规划实例
          const driving = new this.AMap.Driving({
            map: this.map,
            hideMarkers: true,
            showTraffic: true,
            policy: 0, // 最少时间
            outlineColor: strokeColor,
            isOutline: true,
            extensions: 'all',
            panel: false,
            autoFitView: false
          });
          
          // 发起路线规划
          driving.search(start, end, (status, result) => {
            console.log('路线规划结果:', status, result);
            
            if (status === 'complete' && result.routes && result.routes.length) {
              // 获取路径规划方案的第一条路径
              const route = result.routes[0];
              const path = route.path;
              
              // 路线总距离和时间
              const distance = route.distance;
              const time = route.time;
              
              console.log('规划路线成功，距离:', distance, '米，预计时间:', time, '秒');
              
              // 创建折线
              const polyline = new this.AMap.Polyline({
                path: path,
                strokeColor: strokeColor,
                strokeWeight: 6,
                strokeOpacity: 0.8,
                showDir: true,
                dirColor: '#fff',
                borderWeight: 2,
                isOutline: true,
                outlineColor: '#fff',
                lineJoin: 'round'
              });
              
              // 添加到地图
              this.map.add(polyline);
              
              // 在路线上添加行驶距离和时间标注
              const midPoint = path[Math.floor(path.length / 2)];
              const routeInfo = new this.AMap.Text({
                position: midPoint,
                text: `距离: ${(distance / 1000).toFixed(1)}公里 预计: ${Math.ceil(time / 60)}分钟`,
                style: {
                  'padding': '5px 10px',
                  'background-color': strokeColor,
                  'border-radius': '5px',
                  'color': '#fff',
                  'font-size': '12px',
                  'border-width': '0'
                },
                offset: new this.AMap.Pixel(0, -20)
              });
              
              this.map.add(routeInfo);
              
              // 向父组件发送路线信息
              const routeInfoText = `${(distance / 1000).toFixed(1)}公里 ${Math.ceil(time / 60)}分钟`;
              this.$emit('route-info', routeType, routeInfoText);
              
              if (callback) {
                callback(polyline);
              }
            } else {
              console.error('路线规划失败:', result);
              this.$emit('route-info', routeType, '路线规划失败');
            }
          });
        });
      } catch (error) {
        console.error('规划路线出错:', error);
        this.$emit('route-info', routeType, '路线规划出错');
      }
    },
    
    clearMapOverlays() {
      if (!this.isMapLoaded) return;
      
      const overlays = [];
      
      // 收集所有需要清除的覆盖物
      if (this.startMarker) overlays.push(this.startMarker);
      if (this.rescueMarker) overlays.push(this.rescueMarker);
      if (this.endMarker) overlays.push(this.endMarker);
      if (this.startToRescueLine) overlays.push(this.startToRescueLine);
      if (this.rescueToEndLine) overlays.push(this.rescueToEndLine);
      
      // 一次性清除所有覆盖物
      if (overlays.length > 0) {
        this.map.remove(overlays);
      }
      
      // 重置覆盖物引用
      this.startMarker = null;
      this.rescueMarker = null;
      this.endMarker = null;
      this.startToRescueLine = null;
      this.rescueToEndLine = null;
    },
    
    adjustMapView() {
      if (!this.isMapLoaded) return;
      
      try {
        // 获取所有有效的点
        const points = [];
        
        if (this.startPoint && this.startPoint.lat && this.startPoint.lng) {
          points.push([this.startPoint.lng, this.startPoint.lat]);
        }
        
        if (this.rescuePoint && this.rescuePoint.lat && this.rescuePoint.lng) {
          points.push([this.rescuePoint.lng, this.rescuePoint.lat]);
        }
        
        if (this.endPoint && this.endPoint.lat && this.endPoint.lng) {
          points.push([this.endPoint.lng, this.endPoint.lat]);
        }
        
        if (points.length > 1) {
          // 创建包含所有点的边界
          const bounds = new this.AMap.Bounds(
            new this.AMap.LngLat(Math.min(...points.map(p => p[0])), Math.min(...points.map(p => p[1]))),
            new this.AMap.LngLat(Math.max(...points.map(p => p[0])), Math.max(...points.map(p => p[1])))
          );
          
          // 设置地图视野，包含所有标记点
          this.map.setBounds(bounds, {
            padding: [50, 50, 50, 50], // 边界内边距
            duration: 500 // 动画过渡时间
          });
        } else if (points.length === 1) {
          this.map.setCenter(points[0]);
          this.map.setZoom(this.zoom);
        }
      } catch (error) {
        console.error('调整地图视野出错:', error);
      }
    }
  },
  watch: {
    startPoint: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal) && this.isMapLoaded) {
          this.setMapPoints();
        }
      },
      deep: true
    },
    rescuePoint: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal) && this.isMapLoaded) {
          this.setMapPoints();
        }
      },
      deep: true
    },
    endPoint: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal) && this.isMapLoaded) {
          this.setMapPoints();
        }
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.amap-container {
  width: 100%;
  height: 400px;
  background-color: #f5f7fa;
  position: relative;
}

:deep(.amap-logo) {
  display: none !important;
}

:deep(.amap-copyright) {
  display: none !important;
}
</style> 